-module(basetest).

-export([init/4,wait_reply/1,getconfig/1]).

-include("basetest.hrl").

parseconfig([],Config) ->
    Config;
parseconfig([Element|Rest],ConfigBase) ->
    case Element of
	{host,Host} ->
	    Config = ConfigBase#config{host=Host},
	    parseconfig(Rest,Config);
	{port,Port} ->
	    Config = ConfigBase#config{port=Port},
	    parseconfig(Rest,Config);
	_ ->
	    ConfigBase
    end.

getconfig(File) ->
    {ok,Content} = file:consult(File),
    io:format("config file content = ~w~n", [Content]),
    ConfigBase = #config{},
    parseconfig(Content,ConfigBase).

init(Id,Srcid,Dstid,ReqBody) ->
    Ver = <<257:32/little>>,
    Len = <<(string:len(ReqBody)):32/little>>,
    ID = <<Id:32/little>>,
    {A1,A2,A3} = now(),
    random:seed(A1, A2, A3),
    Randum = random:uniform(10000),
    No = <<Randum:32/little>>,

    Srcid1 = Srcid ++ integer_to_list(Randum),
    
    ReqBin = list_to_binary([Ver,Len,ID,No,Srcid1,<<0:((32-string:len(Srcid1))*8)>>,Dstid,<<0:((32-string:len(Dstid))*8)>>,ReqBody]),
    %io:format("Req=~w~n",[ReqBin]),
    ReqBin.

wait_reply(Socket)->
    receive
	{tcp,Socket,Bin}  ->
	    %io:format( "Client  received  binary  =  ~p~n", [Bin]),
	    <<_Ver:32/little,_Len:32/little,_Id:32/little,_No:32/little,Result:32/little,Resp/binary>> = Bin,    
	    %io:format( "Result = ~w, Resp = ~p~n",[Result,binary_to_list(Resp)] ),
	    {ok,Result,binary_to_list(Resp)};
	{tcp_closed,Socket} ->
	    %io:format( "Recv peer close~n" ),
	    {error,peerclose}
    after 5000 ->
	    %io:format( "Recv peer timeout~n" ),
	    {error,recvtimeout}
    end.
